#coding=utf-8

import os, datetime

from flask import Flask
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, current_user
from flask_debugtoolbar import DebugToolbarExtension
from flask_admin import Admin

from config import app_config, DevelopmentConfig

toolbar = DebugToolbarExtension()
db = SQLAlchemy()
mail_sender = Mail()
admin = Admin(name='microblog', template_mode='bootstrap3')

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'blue_auth.login'
login_manager.login_message = u"请 先 登 录"
login_manager.login_message_category = 'waring'
login_manager.remember_cookie_duration = datetime.timedelta(hours=1)

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(app_config[config_name])
    app_config[config_name].init_app(app)


    if app_config[config_name] == DevelopmentConfig:
        dbfile_path = app_config[config_name].SQLALCHEMY_DATABASE_URI.replace('sqlite:///', '')
        db_path, db_filename = os.path.split(dbfile_path)
        if not os.path.exists(db_path):
            os.mkdir(db_path)
        #
    else:
        pass
    #

    toolbar.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail_sender.init_app(app)
    admin.init_app(app)

    from .BlueAuth import blue_auth
    app.register_blueprint(blue_auth, url_prefix='/auth')

    from .BlueDuty import blue_duty
    app.register_blueprint(blue_duty)

    from .BlueMain import blue_main
    app.register_blueprint(blue_main, url_prefix='/main')

    return app